package manager.entitycreator;

import java.sql.ResultSet;
import java.sql.SQLException;

import controller.RoundCtrl;
import entity.Bid;
import entity.Round;
import entity.Section;
import entity.Student;

/**
 * Implements methods that describe how to extract bid information from the
 * given ResultSet.
 * 
 * @author sheryl.tay, mohameds.2012
 * 
 */
public class BidCreator implements EntityCreator<Bid> {

	@Override
	public Bid newEntityFromResultSet(ResultSet rs) throws SQLException {
		return newBidFromResultSet(rs);
	}

	/**
	 * Creates a new Bid entity from the given result set.
	 * 
	 * @param rs
	 *            result set containing student, section and bid information
	 * @return a new Bid entity with information extracted from the result set
	 * @throws SQLException
	 */
	static Bid newBidFromResultSet(ResultSet rs) throws SQLException {
		Student student = StudentCreator.newStudentFromResultSet(rs);

		Section section = SectionCreator.newSectionFromResultSet(rs);

		double bidAmount = 0.0;
		int bidRoundNo = rs.getInt("bidRoundNo");

		// use try-catch to obtain bidAmount
		// because only some SQL statements ask for it
		try {
			bidAmount = rs.getDouble("section_student_bidAmount");
		} catch (SQLException e) {
			bidAmount = rs.getDouble("bid_bidAmount");
		}

		// use try-catch to obtain bidResult
		// because only some SQL statements ask for it
		try {
			// assume that result set has the bidResult column
			// try and obtain the bidResult column
			String bidResult = rs.getString("bidResult");
			Bid bid = new Bid(student, section, bidAmount, bidResult, bidRoundNo);
			
			// bid result for round two
			RoundCtrl roundCtrl = new RoundCtrl();
			if(roundCtrl.isCurrentRoundNo(Round.ROUND_TWO) && roundCtrl.isCurrentRoundOpen()) {
				bidResult = roundCtrl.getStatusForBid(bid);
				bid.setBidResult(bidResult);
			}
			
			return bid;
		} catch (SQLException e) {
			// oops! bidResult column was not found in the result set
			// seems like SQL select statement did not ask for the bidResult
			return new Bid(student, section, bidAmount, bidRoundNo);
		}
	}

}
